/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.tracer.core;

import com.lvyh.lightframe.tracer.core.common.TraceContants;
import com.lvyh.lightframe.tracer.core.util.StringUtils;
import io.opentracing.SpanContext;
import io.opentracing.propagation.TextMapExtract;

import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

class TextMapContext implements SpanContext {

    public static final String RPC_ID_SEPARATOR = ".";

    private String traceId = "";

    private String spanId = "";

    private String parentId = "";

    private final TextMapExtract textMap;

    public TextMapContext(TextMapExtract carrier) {
        this.textMap = carrier;

        Iterator<Map.Entry<String, String>> iterator = this.textMap.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            if (Objects.equals(entry.getKey(), TraceContants.TRACE_ID_ALIAS)) {
                this.setTraceId(entry.getValue());
            }
            if (Objects.equals(entry.getKey(), TraceContants.SPAN_ID_ALIAS)) {
                this.setSpanId(entry.getValue());
            }
        }
    }

    @Override
    public Iterable<Map.Entry<String, String>> baggageItems() {
        return textMap;
    }

    @Override
    public String toSpanId() {
        return getSpanId();
    }

    @Override
    public String toTraceId() {
        return getTraceId();
    }

    public void setTraceId(String traceId) {
        this.traceId = traceId;
    }

    public void setSpanId(String spanId) {
        this.spanId = spanId;
        this.parentId = this.genParentSpanId(spanId);
    }

    private String genParentSpanId(String spanId) {
        return (StringUtils.isBlank(spanId) || spanId.lastIndexOf(RPC_ID_SEPARATOR) < 0) ? ""
                : spanId.substring(0, spanId.lastIndexOf(RPC_ID_SEPARATOR));
    }

    public String getTraceId() {
        return StringUtils.isBlank(this.traceId) ? "" : traceId;
    }

    public String getSpanId() {
        return StringUtils.isBlank(spanId) ? "" : spanId;
    }

    public String getParentId() {
        return StringUtils.isBlank(parentId) ? "" : parentId;
    }
}
